package com.wzy.oa_sys.service.impl.login;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzy.oa_sys.mapper.user.UserMapper;
import com.wzy.oa_sys.model.pojo.user.OaUser;
import com.wzy.oa_sys.service.login.LoginService;
import com.wzy.oa_sys.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Service
public class LoginServiceImpl implements LoginService {

    @Value("${jwt.secret}")
    private String SECRET;

    private static final long EXPIRATION_TIME = 86400000; // 1 天，单位是毫秒

    @Autowired
    private UserMapper userMapper;

    // 示例：这里可以连接数据库查询用户信息
    public boolean validateUser(String username, String password) {
        // 实际情况中，应对接数据库验证用户
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_account", username);
        OaUser user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return false;
        }
        password = encryptPassword(password);
        System.out.println("password: " + password);
        System.out.println("username"+username);
        return user.getCAccount().equals(username) && user.getCPassword().equals(password);
    }

    //MD5加密密码
    private String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte[] byteData = md.digest();

            // Convert the byte to hex format
            StringBuilder sb = new StringBuilder();
            for (byte b : byteData) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error encrypting password", e);
        }
    }

    // 生成 token 的方法
    public String generateToken(String username) {
        System.out.println(SECRET);
        Algorithm algorithm = Algorithm.HMAC256(SECRET); // 使用 HMAC256 算法
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_account", username);
        OaUser user = userMapper.selectOne(queryWrapper);
        StringBuilder sb = new StringBuilder();
        if(user.getNRole() == 1){
            sb.append("SUPERMAN");
        }else if(user.getNRole() == 2){
            sb.append("MANAGER");
        }else{
            sb.append("NORMAL");
        }
        String token = JWT.create()
                .withSubject(username) // 设置 token 的主题
                .withClaim("role", sb.toString())
                .withClaim("userId", user.getNUserId())
                .withClaim("deptId",user.getNDeptId())
                .withIssuedAt(new Date(System.currentTimeMillis())) // 签发时间
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) // 设置过期时间
                .sign(algorithm); // 生成 token

        return token; // 返回生成的 token
    }
}
